import React, { Component } from "react";
import PubSub from "pubsub-js";
// import axios from 'axios'
import "./index.css";

export default class Search extends Component {
  searchByKeyword = async () => {
    /* //获取用户的输入（连续解构赋值+重命名）
    const {keyWordElement:{value: keyword}} = this
    //发送请求前通知List更新状态
    PubSub.publish('atguigu',{isFirst: false,isLoading:true})
    //发送网络请求
    axios.get(`/api1/search/users?q=${keyword}`).then(
      //请求成功后通知List更新状态
      response => PubSub.publish('atguigu',{isLoading:false,users:response.data.items}),
      //请求失败后通知List更新状态
      error => PubSub.publish('atguigu',{isLoading:false,err: error.message})
    ) */

    /* const {
      keyWordElement: { value: keyword },
    } = this;
    fetch(`/api1/search/usersdd?q=${keyword}`)
      .then(
        (response) => {
          console.log("请求服务器成功")
          return response.json();
        },
        (error) => {
          console.log("请求服务器失败")
        }
      )
      .then(
        (response) => console.log("获取数据成功", response),
        (error) => console.log("获取数据失败", error)
      ); */

    /* const {
      keyWordElement: { value: keyword },
    } = this;
    fetch(`/api1/search/usersdd?q=${keyword}`)
      .then(
        (response) => {
          console.log("请求服务器成功");
          return response.json();
        },
        (error) => {
          console.log("请求服务器失败");
          return new Promise(() => {});
        }
      )
      .then(
        (response) => console.log("获取数据成功", response),
        (error) => console.log("获取数据失败", error)
      ); */

    try {
      const {
        keyWordElement: { value: keyword },
      } = this;
      //发送请求前通知List更新状态
      PubSub.publish("atguigu", { isFirst: false, isLoading: true });
      var response = await fetch(`/api1/search/users?q=${keyword}`);
      var data = await response.json();
      //请求成功后通知List更新状态
      PubSub.publish("atguigu", { isLoading: false, users: data.items });
    } catch (error) {
      //请求失败后通知List更新状态
      PubSub.publish("atguigu", { isLoading: false, err: error.message });
    }
  };
  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">Search Github Users</h3>
        <div>
          <input
            ref={(c) => (this.keyWordElement = c)}
            type="text"
            placeholder="enter the name you search"
          />
          &nbsp;<button onClick={this.searchByKeyword}>Search</button>
        </div>
      </section>
    );
  }
}
